<template>
  <s-clean-layout :title="isEdit ? '编辑事件' : '添加事件'" navbar="normal">
    <view class="event-edit-container">
      <!-- 表单内容 -->
      <scroll-view scroll-y class="form-container">
        <!-- 发起人 -->
        <view class="form-item" @tap="selectInitiator">
          <view class="label">发起人</view>
          <view class="value-container">
            <view class="selected-user" v-if="formData.initiator">
              <view class="avatar-container">
                <image v-if="formData.initiatorAvatar" class="avatar" :src="formData.initiatorAvatar" mode="aspectFill"></image>
                <view v-else class="avatar-placeholder">
                  <text>{{ getNameInitial(formData.initiator) }}</text>
                </view>
              </view>
              <text>{{ formData.initiator }}</text>
            </view>
          </view>
          <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
        </view>

        <!-- 移除参与人部分 -->

        <!-- 类型 -->
        <view class="form-item" @tap="selectType">
          <view class="label">类型</view>
          <view class="value-container">
            <view class="type-tag">{{ formData.type }}</view>
          </view>
          <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
        </view>

        <!-- 状态 -->
        <view class="form-item" @tap="selectStatus">
          <view class="label">状态</view>
          <view class="value-container">
            <view class="status-tag" :class="getStatusClass(formData.status)">{{ formData.status }}</view>
          </view>
          <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
        </view>

        <!-- 日期时间 -->
        <view class="form-item" @tap="selectDateTime">
          <view class="label">事件时间</view>
          <view class="value-container">
            <view class="date-time">
              <text class="date">{{ formData.date }}</text>
              <text class="time">{{ formData.time }}</text>
            </view>
          </view>
          <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
        </view>

        <!-- 添加提醒时间 -->
        <view class="form-item" @tap="selectReminder">
          <view class="label">提醒时间</view>
          <view class="value-container">
            <view class="reminder-value">{{ formData.reminder }}</view>
          </view>
          <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
        </view>

        <!-- 添加重复类型 -->
        <view class="form-item" @tap="selectRepeatType">
          <view class="label">重复类型</view>
          <view class="value-container">
            <view class="repeat-type-value">{{ getRepeatTypeText(formData.repeatType) }}</view>
          </view>
          <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
        </view>

        <!-- 标题 -->
        <view class="form-item">
          <view class="label">标题</view>
          <view class="value-container">
            <input class="event-title-input" v-model="formData.title" placeholder="请输入事件标题" />
          </view>
        </view>

        <!-- 描述 -->
        <view class="form-item">
          <view class="label">描述</view>
          <view class="value-container">
            <textarea class="event-content-input" v-model="formData.description" placeholder="请输入事件描述" />
          </view>
        </view>

        <!-- 图片 -->
        <view class="form-item">
          <view class="label">图片</view>
          <view class="value-container">
            <view class="image-list">
              <view v-for="(image, index) in formData.images" :key="index" class="image-item">
                <image :src="image" mode="aspectFill" @tap="previewImage(index)"></image>
                <view class="delete-btn" @tap.stop="deleteImage(index)">
                  <text class="delete-icon">×</text>
                </view>
              </view>
              <view class="add-image" @tap="addImage" v-if="formData.images.length < 9">
                <uni-icons class="add-image-icon" type="plusempty" size="20" color="#999"></uni-icons>
                <text class="add-image-text">添加图片</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 底部间距，确保内容不被底部保存按钮遮挡 -->
        <view style="height: 120rpx;"></view>
      </scroll-view>
      
      <!-- 底部保存按钮 -->
      <view class="bottom-save-button" @tap="saveEvent">
        <text>保存</text>
      </view>

      <!-- 使用人员选择组件 -->
      <s-contact-selector
        v-model:visible="showContactSelector"
        :title="selectorMode === 'initiator' ? '选择发起人' : ''"
        :contacts="contactsList"
        :filter-tabs="filterTabs"
        :multiple="false"
        v-model="tempSelectedContacts"
        @confirm="handleContactConfirm"
      />

      <!-- 使用状态选择组件 -->
      <s-dropdown-selector
        v-model:visible="showStatusSelector"
        title="状态"
        :options="statusOptions"
        v-model="formData.status"
      />

      <!-- 使用日期时间选择器组件 -->
      <s-datetime-picker
        v-model:visible="showDateTimeSelector"
        :title="dateTimeTitle"
        :initial-date="getInitialDateValue()"
        @confirm="handleDateTimeConfirm"
        @cancel="closeDateTimeSelector"
      />

      <!-- 添加提醒选择器组件 -->
      <s-reminder-selector
        v-model:visible="showReminderSelector"
        :value="formData.reminder"
        @confirm="handleReminderConfirm"
      />

      <!-- 添加重复类型选择器组件 -->
      <s-dropdown-selector
        v-model:visible="showRepeatTypeSelector"
        title="重复类型"
        :options="repeatTypeOptions"
        v-model="selectedRepeatType"
        @confirm="handleRepeatTypeConfirm"
      />

      <!-- 使用类型管理组件 -->
      <s-type-manage
        v-model:visible="showTypeSelector"
        :busin-type="'CONTACT_EVENT'"
        :page-title="'事件类型'"
        @type-selected="handleTypeSelected"
      />
    </view>
  </s-clean-layout>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import EventApi from '@/pages/contact/api/event';
import ContactApi from '@/sheep/api/contact/contact';
import FileApi from '@/sheep/api/infra/file'; // 添加FileApi导入
// import TypeManage from '@/sheep/components/s-type-manage/type-manage.vue'; // 添加组件导入

const isEdit = ref(false);
const formData = reactive({
  id: null,
  contactId: null,
  categoryId: null,
  dealStatus: 0,
  eventName: '',
  eventContent: '',
  eventDate: '',
  reminderEnabled: 1,
  advanceReminderDays: 1,
  advanceReminderTime: '09:00:00',
  repeatType: 0,
  remark: '',
  // 临时字段，用于UI展示
  initiator: '',
  initiatorAvatar: '',
  type: '读书',
  status: '未完成',
  date: '',
  time: '',
  title: '',
  description: '',
  reminder: '提前1天 09:00',
  images: [], // 用于UI展示的图片数组
  fileUrls: '', // 用于保存的图片URL字符串
});

// 添加状态选择相关变量
const showStatusSelector = ref(false);
const statusOptions = ['未完成', '已完成', '已放弃'];

// 添加提醒选择相关变量
const showReminderSelector = ref(false);

// 添加重复类型选择相关变量
const showRepeatTypeSelector = ref(false);
const repeatTypeOptions = ['不重复', '每天', '每周', '每月', '每年'];
const selectedRepeatType = ref('不重复');

// 移除参与人相关变量
// const participants = ref([...]);

// 人员选择相关
const showContactSelector = ref(false);
const selectorMode = ref('initiator'); // 只保留 'initiator' 模式
const filterTabs = ['全部', '女儿', '小孩'];
const currentFilterTab = ref(0);
const tempSelectedContacts = ref([]);

// 模拟联系人数据
const contactsList = ref([
  { id: '1', name: 'Me', avatar: '' },
  { id: '2', name: '汤圆', avatar: '' },
  { id: '3', name: '小明', avatar: '', group: '小孩' },
  { id: '4', name: '小红', avatar: '', group: '女儿' }
]);

// 添加类型选择器显示控制
const showTypeSelector = ref(false);

// 获取姓名首字母
const getNameInitial = (name) => {
  if (!name) return '?';
  return name.charAt(0).toUpperCase();
};

// 打开联系人选择器 - 发起人模式
const selectInitiator = () => {
  selectorMode.value = 'initiator';
  tempSelectedContacts.value = formData.initiator ? [{ id: '0', name: formData.initiator, avatar: formData.initiatorAvatar }] : [];
  showContactSelector.value = true;
};

// 移除参与人选择方法
// const selectParticipants = () => {...};

// 处理联系人选择确认
const handleContactConfirm = (selectedContacts) => {
  if (selectorMode.value === 'initiator') {
    // 发起人模式
    if (selectedContacts.length > 0) {
      const selected = selectedContacts[0];
      formData.initiator = selected.name;
      formData.initiatorAvatar = selected.avatar || '';
    }
  }
  // 移除参与人模式处理
};

// 根据状态获取样式类名
const getStatusClass = (status) => {
  const classMap = {
    '未完成': 'status-pending',
    '已放弃': 'status-abandoned',
    '已完成': 'status-completed'
  };
  
  return classMap[status] || 'status-pending';
};

// 获取重复类型文本
const getRepeatTypeText = (repeatType) => {
  const typeMap = {
    0: '不重复',
    1: '每天',
    2: '每周',
    3: '每月',
    4: '每年'
  };
  
  return typeMap[repeatType] || '不重复';
};

// 返回上一页
const goBack = () => {
  // 获取当前页面
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const { contactId } = currentPage.options;
  
  // 如果有未保存的更改，可以添加提示
  // 直接返回到事件列表页面
  uni.navigateBack({
    delta: 1,
    success: function() {
      console.log('返回到事件列表页面');
    }
  });
};

// 保存事件
const saveEvent = async () => {
  if (!formData.title) {
    uni.showToast({
      title: '请输入事件名称',
      icon: 'none'
    });
    return;
  }
  
  if (!formData.categoryId) {
    uni.showToast({
      title: '请选择事件类型',
      icon: 'none'
    });
    return;
  }
  
  try {
    uni.showLoading({
      title: isEdit.value ? '更新中...' : '添加中...'
    });
    
    // 解析提醒设置
    let reminderEnabled = 1;
    let advanceReminderDays = 1;
    let advanceReminderTime = "09:00:00";
    
    if (formData.reminder.includes('不提醒')) {
      reminderEnabled = 0;
      advanceReminderDays = null;
      advanceReminderTime = null;
    } else if (formData.reminder.includes('提前')) {
      reminderEnabled = 1;
      const daysMatch = formData.reminder.match(/提前(\d+)天/);
      if (daysMatch) {
        advanceReminderDays = parseInt(daysMatch[1]);
      }
      
      const timeMatch = formData.reminder.match(/(\d{1,2}:\d{2})/);
      if (timeMatch) {
        advanceReminderTime = timeMatch[1] + ":00";
      }
    } else if (formData.reminder.includes('当天')) {
      reminderEnabled = 1;
      advanceReminderDays = 0;
      
      const timeMatch = formData.reminder.match(/(\d{1,2}:\d{2})/);
      if (timeMatch) {
        advanceReminderTime = timeMatch[1] + ":00";
      }
    }
    
    // 构建日期时间
    const dateTime = new Date(`${formData.date} ${formData.time}`);
    
    // 构建状态值
    const statusMap = {
      '未完成': 0,
      '已完成': 1,
      '已放弃': 2
    };
    
    // 构建请求参数
    const params = {
      id: formData.id,
      contactId: formData.contactId,
      categoryId: formData.categoryId,
      dealStatus: statusMap[formData.status] || 0,
      eventName: formData.title,
      eventContent: formData.description,
      eventDate: dateTime.getTime(),
      reminderEnabled: reminderEnabled,
      advanceReminderDays: advanceReminderDays,
      advanceReminderTime: advanceReminderTime,
      repeatType: formData.repeatType,
      remark: '',
      fileUrls: formData.fileUrls // 添加文件URLs字段
    };
    
    // 调用接口
    const res = await EventApi.addOrUpdateContactEvent(params);
    
    uni.hideLoading();
    
    if (res.code === 0) {
      // 如果是新增事件，保存返回的事件ID
      if (!isEdit.value && res.data) {
        formData.id = res.data;
      }
      
      uni.showToast({
        title: isEdit.value ? '更新成功' : '添加成功',
        icon: 'success'
      });
      
      // 移除使用 eventChannel 通知的方式
      // 直接设置一个标记，表示数据已更新
      uni.setStorageSync('eventListNeedRefresh', true);
      
      setTimeout(() => {
        uni.navigateBack();
      }, 500);
    } else {
      uni.showToast({
        title: res.msg || (isEdit.value ? '更新失败' : '添加失败'),
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('保存事件失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  }
};

// 选择类型
const selectType = () => {
  // 跳转到类型管理页面
  uni.navigateTo({
    url: `/pages/comm/type-manage?businType=CONTACT_EVENT&pageTitle=事件类型`
  });
};

// 处理类型选择
const handleTypeSelected = (type) => {
  console.log('选择的事件类型:', type);
  formData.categoryId = type.id;
  formData.type = type.name;
  formData.typeIcon = type.icon;
  formData.typeColor = type.color;
};

// 选择状态
const selectStatus = () => {
  showStatusSelector.value = true;
};

// 修改日期时间选择相关变量
const showDateTimeSelector = ref(false);
const dateTimeTitle = ref('选择日期和时间');

// 获取初始日期时间值
const getInitialDateValue = () => {
  if (formData.date && formData.time) {
    return new Date(`${formData.date} ${formData.time}`);
  }
  return new Date();
};

// 处理日期时间确认
const handleDateTimeConfirm = (data) => {
  formData.date = data.date;
  formData.time = data.time.substring(0, 5); // 只保留时:分
};

// 关闭日期时间选择器
const closeDateTimeSelector = () => {
  showDateTimeSelector.value = false;
};

// 选择日期时间
const selectDateTime = () => {
  showDateTimeSelector.value = true;
};

// 选择提醒时间
const selectReminder = () => {
  showReminderSelector.value = true;
};

// 处理提醒时间确认
const handleReminderConfirm = (reminderValue) => {
  formData.reminder = reminderValue;
  
  // 如果选择了不提醒，则设置reminderEnabled为0
  if (reminderValue.includes('不提醒')) {
    formData.reminderEnabled = 0;
  } else {
    formData.reminderEnabled = 1;
  }
};

// 选择重复类型
const selectRepeatType = () => {
  selectedRepeatType.value = getRepeatTypeText(formData.repeatType);
  showRepeatTypeSelector.value = true;
};

// 处理重复类型确认
const handleRepeatTypeConfirm = (value) => {
  // 将文本转换为数值
  const typeMap = {
    '不重复': 0,
    '每天': 1,
    '每周': 2,
    '每月': 3,
    '每年': 4
  };
  
  formData.repeatType = typeMap[value] || 0;
};

// 添加图片
const addImage = async () => {
  uni.chooseImage({
    count: 9,
    success: async (res) => {
      // 上传选中的图片
      for (const tempFilePath of res.tempFilePaths) {
        const result = await FileApi.uploadFile(tempFilePath);
        if (result && result.data) {
          formData.images.push(result.data);
        }
      }
      // 更新fileUrls
      formData.fileUrls = formData.images.join(',');
    }
  });
};

// 添加预览图片方法
const previewImage = (index) => {
  uni.previewImage({
    urls: formData.images,
    current: formData.images[index]
  });
};

// 添加删除图片方法
const deleteImage = (index) => {
  formData.images.splice(index, 1);
  formData.fileUrls = formData.images.join(',');
};

// 初始化页面数据
const initPageData = async () => {
  // 获取当前页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const { mode, id, contactId } = currentPage.options;
  
  // 设置联系人ID
  formData.contactId = contactId;
  
  // 判断是编辑模式还是添加模式
  isEdit.value = mode === 'edit';
  
  if (isEdit.value && id) {
    try {
      uni.showLoading({
        title: '加载中...'
      });
      
      // 调用接口获取事件详情
      const res = await EventApi.queryContactEvents({
        contactId: contactId
      });
      
      uni.hideLoading();
      
      if (res.code === 0 && res.data) {
        // 查找对应ID的事件
        const event = res.data.find(item => item.id == id);
        
        if (event) {
          // 填充表单数据
          formData.id = event.id;
          formData.contactId = event.contactId;
          formData.categoryId = event.categoryId;
          formData.title = event.eventName;
          formData.description = event.eventContent;
          
          // 处理状态
          const statusTextMap = {
            0: '未完成',
            1: '已完成',
            2: '已放弃'
          };
          formData.status = statusTextMap[event.dealStatus] || '未完成';
          formData.dealStatus = event.dealStatus;
          
          // 处理日期和时间
          if (event.eventDate) {
            const date = new Date(event.eventDate);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            formData.date = `${year}-${month}-${day}`;
            formData.time = `${hours}:${minutes}`;
          }
          
          // 处理提醒设置
          formData.reminderEnabled = event.reminderEnabled;
          formData.advanceReminderDays = event.advanceReminderDays;
          formData.advanceReminderTime = event.advanceReminderTime;
          
          // 构建提醒文本
          if (event.reminderEnabled === 0) {
            formData.reminder = '不提醒';
          } else {
            const days = event.advanceReminderDays || 0;
            const time = event.advanceReminderTime ? event.advanceReminderTime.substring(0, 5) : '09:00';
            
            if (days === 0) {
              formData.reminder = `当天 ${time}`;
            } else {
              formData.reminder = `提前${days}天 ${time}`;
            }
          }
          
          // 设置重复类型
          formData.repeatType = event.repeatType || 0;
          
          // 获取事件类型名称
          // TODO: 根据categoryId获取类型名称
          // 暂时使用默认值
          formData.type = '读书';

          // 处理图片URLs
          if (event.fileUrls) {
            formData.fileUrls = event.fileUrls;
            formData.images = event.fileUrls.split(',');
          }
        }
      } else {
        uni.showToast({
          title: '获取事件详情失败',
          icon: 'none'
        });
      }
    } catch (error) {
      uni.hideLoading();
      console.error('获取事件详情失败:', error);
      uni.showToast({
        title: '网络异常，请稍后重试',
        icon: 'none'
      });
    }
  } else {
    // 添加模式：设置默认值
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    
    formData.date = `${year}-${month}-${day}`;
    formData.time = `${hours}:${minutes}`;
    formData.reminder = '提前1天 09:00';
    formData.repeatType = 0;
    formData.reminderEnabled = 1;
    formData.status = '未完成';
  }
};

// 添加 onShow 生命周期函数
onShow(() => {
  // 检查是否有从类型选择页面返回的数据
  const selectedType = uni.getStorageSync('selectedEventType');
  if (selectedType) {
    console.log('检测到类型选择:', selectedType);
    
    // 判断selectedType是对象还是字符串
    if (typeof selectedType === 'object') {
      // 新的格式：对象，包含id、name和icon
      formData.categoryId = selectedType.id;
      formData.type = selectedType.name;
      formData.typeIcon = selectedType.icon;
    } else {
      // 旧的格式：只有类型名称的字符串
      formData.type = selectedType;
      // 注意：这种情况下没有设置categoryId，会导致保存时提示选择类型
    }
    
    // 使用后清除
    uni.removeStorageSync('selectedEventType');
  }
});

// 页面加载时初始化数据
// 在onMounted中添加获取联系人信息的逻辑
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const { id, contactId, mode, contactName, contactImg } = currentPage.options;
  
  // 设置编辑模式
  isEdit.value = mode === 'edit';
  
  // 设置联系人ID
  if (contactId) {
    formData.contactId = contactId;
    
    // 如果URL中传递了联系人名称和头像，直接使用
    if (contactName) {
      formData.initiator = decodeURIComponent(contactName);
    }
    
    if (contactImg) {
      formData.initiatorAvatar = decodeURIComponent(contactImg);
    }
    
    // 如果没有传递联系人信息，则通过API获取
    if (!contactName) {
      getContactInfo(contactId);
    }
  }
  
  // 如果是编辑模式，加载事件详情
  if (isEdit.value && id) {
    loadEventDetail(id);
  } else {
    // 设置默认日期和时间
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    
    formData.date = `${year}-${month}-${day}`;
    formData.time = `${hours}:${minutes}`;
  }
});

// 获取联系人信息
const getContactInfo = async (contactId) => {
  try {
    const res = await ContactApi.queryContactDetail({ id: contactId });
    
    if (res.code === 0 && res.data) {
      // 设置发起人信息
      formData.initiator = res.data.name || '';
      formData.initiatorAvatar = res.data.avatarUrl || '';
    }
  } catch (error) {
    console.error('获取联系人信息失败:', error);
  }
};

// 加载事件详情
const loadEventDetail = async (id) => {
  try {
    uni.showLoading({
      title: '加载中...'
    });
    
    // 修改为使用正确的API方法获取事件详情
    // 方法一：使用queryContactEvents获取所有事件，然后筛选
    const res = await EventApi.queryContactEvents({
      contactId: formData.contactId,
      id: id // 可能需要添加id参数，取决于后端API的实现
    });
    
    uni.hideLoading();
    
    if (res.code === 0 && res.data) {
      // 查找对应ID的事件
      const eventData = res.data.find(item => item.id == id);
      
      if (eventData) {
        // 填充表单数据
        formData.id = eventData.id;
        formData.contactId = eventData.contactId;
        formData.categoryId = eventData.categoryId;
        formData.title = eventData.eventName;
        formData.description = eventData.eventContent;
        formData.repeatType = eventData.repeatType || 0;
        
        // 设置状态
        const statusTextMap = {
          0: '未完成',
          1: '已完成',
          2: '已放弃'
        };
        formData.status = statusTextMap[eventData.dealStatus] || '未完成';
        
        // 设置日期和时间
        if (eventData.eventDate) {
          const date = new Date(eventData.eventDate);
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          const hours = String(date.getHours()).padStart(2, '0');
          const minutes = String(date.getMinutes()).padStart(2, '0');
          
          formData.date = `${year}-${month}-${day}`;
          formData.time = `${hours}:${minutes}`;
        }
        
        // 设置提醒
        if (eventData.reminderEnabled === 0) {
          formData.reminder = '不提醒';
        } else {
          const days = eventData.advanceReminderDays || 0;
          const time = eventData.advanceReminderTime ? eventData.advanceReminderTime.substring(0, 5) : '09:00';
          
          if (days === 0) {
            formData.reminder = `当天 ${time}`;
          } else {
            formData.reminder = `提前${days}天 ${time}`;
          }
        }
        
        // 设置类型
        formData.type = eventData.categoryName || '读书';
        
        // 如果有发起人信息，则设置
        if (eventData.initiator) {
          formData.initiator = eventData.initiator;
          formData.initiatorAvatar = eventData.initiatorAvatar || '';
        }

        // 处理图片URLs
        if (eventData.fileUrls) {
          formData.fileUrls = eventData.fileUrls;
          formData.images = eventData.fileUrls.split(',');
        }
      } else {
        uni.showToast({
          title: '未找到事件详情',
          icon: 'none'
        });
      }
    } else {
      uni.showToast({
        title: res.msg || '获取事件详情失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('获取事件详情失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  }
};
</script>

<style lang="scss" scoped>
// 引入 event-edit.scss
@import './styles/event-edit.scss';
</style>
